3 * Blocks and bans object
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use MediaWiki\MediaWikiServices
;
44 public $mParentBlockId;
50 protected $mFromMaster;
53 protected $mBlockEmail;
56 protected $mDisableUsertalk;
59 protected $mCreateAccount;
61 /** @var User|string */
64 /** @var int Hack for foreign blocking (CentralAuth) */
65 protected $forcedTargetID;
67 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
74 protected $isHardblock;
77 protected $isAutoblocking;
79 /** @var string|null */
80 protected $systemBlockType;
90 * Create a new block with specified parameters on a user, IP or IP range.
92 * @param array $options Parameters of the block:
93 * address string|User Target user name, User object, IP address or IP range
94 * user int Override target user ID (for foreign users)
95 * by int User ID of the blocker
96 * reason string Reason of the block
97 * timestamp string The time at which the block comes into effect
98 * auto bool Is this an automatic block?
99 * expiry string Timestamp of expiration of the block or 'infinity'
100 * anonOnly bool Only disallow anonymous actions
101 * createAccount bool Disallow creation of new accounts
102 * enableAutoblock bool Enable automatic blocking
103 * hideName bool Hide the target user name
104 * blockEmail bool Disallow sending emails
105 * allowUsertalk bool Allow the target to edit its own talk page
106 * byText string Username of the blocker (for foreign users)
107 * systemBlock string Indicate that this block is automatically
108 * created by MediaWiki rather than being stored
109 * in the database. Value is a string to return
110 * from self::getSystemBlockType().
112 * @since 1.26 accepts $options array instead of individual parameters; order
113 * of parameters above reflects the original order
115 function __construct( $options = [] ) {
125 'createAccount' => false,
126 'enableAutoblock' => false,
128 'blockEmail' => false,
129 'allowUsertalk' => false,
131 'systemBlock' => null,
134 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
135 $options = array_combine(
136 array_slice( array_keys( $defaults ), 0, func_num_args() ),
139 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
142 $options +
= $defaults;
144 $this->setTarget( $options['address'] );
146 if ( $this->target
instanceof User
&& $options['user'] ) {
147 # Needed for foreign users
148 $this->forcedTargetID
= $options['user'];
151 if ( $options['by'] ) {
153 $this->setBlocker( User
::newFromId( $options['by'] ) );
156 $this->setBlocker( $options['byText'] );
159 $this->mReason
= $options['reason'];
160 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
161 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
164 $this->mAuto
= (bool)$options['auto'];
165 $this->mHideName
= (bool)$options['hideName'];
166 $this->isHardblock( !$options['anonOnly'] );
167 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
169 # Prevention measures
170 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
171 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
172 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
174 $this->mFromMaster
= false;
175 $this->systemBlockType
= $options['systemBlock'];
179 * Load a blocked user from their block id.
181 * @param int $id Block id to search for
184 public static function newFromID( $id ) {
185 $dbr = wfGetDB( DB_REPLICA
);
186 $res = $dbr->selectRow(
188 self
::selectFields(),
193 return self
::newFromRow( $res );
200 * Return the list of ipblocks fields that should be selected to create
204 public static function selectFields() {
214 'ipb_create_account',
215 'ipb_enable_autoblock',
219 'ipb_allow_usertalk',
220 'ipb_parent_block_id',
225 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
226 * the blocking user or the block timestamp, only things which affect the blocked user
228 * @param Block $block
232 public function equals( Block
$block ) {
234 (string)$this->target
== (string)$block->target
235 && $this->type
== $block->type
236 && $this->mAuto
== $block->mAuto
237 && $this->isHardblock() == $block->isHardblock()
238 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
239 && $this->mExpiry
== $block->mExpiry
240 && $this->isAutoblocking() == $block->isAutoblocking()
241 && $this->mHideName
== $block->mHideName
242 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
243 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
244 && $this->mReason
== $block->mReason
249 * Load a block from the database which affects the already-set $this->target:
250 * 1) A block directly on the given user or IP
251 * 2) A rangeblock encompassing the given IP (smallest first)
252 * 3) An autoblock on the given IP
253 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
254 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
255 * @throws MWException
256 * @return bool Whether a relevant block was found
258 protected function newLoad( $vagueTarget = null ) {
259 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
261 if ( $this->type
!== null ) {
263 'ipb_address' => [ (string)$this->target
],
266 $conds = [ 'ipb_address' => [] ];
269 # Be aware that the != '' check is explicit, since empty values will be
270 # passed by some callers (T31116)
271 if ( $vagueTarget != '' ) {
272 list( $target, $type ) = self
::parseTarget( $vagueTarget );
274 case self
::TYPE_USER
:
275 # Slightly weird, but who are we to argue?
276 $conds['ipb_address'][] = (string)$target;
280 $conds['ipb_address'][] = (string)$target;
281 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
282 $conds = $db->makeList( $conds, LIST_OR
);
285 case self
::TYPE_RANGE
:
286 list( $start, $end ) = IP
::parseRange( $target );
287 $conds['ipb_address'][] = (string)$target;
288 $conds[] = self
::getRangeCond( $start, $end );
289 $conds = $db->makeList( $conds, LIST_OR
);
293 throw new MWException( "Tried to load block with invalid type" );
297 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
299 # This result could contain a block on the user, a block on the IP, and a russian-doll
300 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
303 # Lower will be better
304 $bestBlockScore = 100;
306 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
307 $bestBlockPreventsEdit = null;
309 foreach ( $res as $row ) {
310 $block = self
::newFromRow( $row );
312 # Don't use expired blocks
313 if ( $block->isExpired() ) {
317 # Don't use anon only blocks on users
318 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
322 if ( $block->getType() == self
::TYPE_RANGE
) {
323 # This is the number of bits that are allowed to vary in the block, give
324 # or take some floating point errors
325 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
326 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
327 $size = log( $end - $start +
1, 2 );
329 # This has the nice property that a /32 block is ranked equally with a
330 # single-IP block, which is exactly what it is...
331 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
334 $score = $block->getType();
337 if ( $score < $bestBlockScore ) {
338 $bestBlockScore = $score;
340 $bestBlockPreventsEdit = $block->prevents( 'edit' );
344 if ( $bestRow !== null ) {
345 $this->initFromRow( $bestRow );
346 $this->prevents( 'edit', $bestBlockPreventsEdit );
354 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
355 * @param string $start Hexadecimal IP representation
356 * @param string $end Hexadecimal IP representation, or null to use $start = $end
359 public static function getRangeCond( $start, $end = null ) {
360 if ( $end === null ) {
363 # Per T16634, we want to include relevant active rangeblocks; for
364 # rangeblocks, we want to include larger ranges which enclose the given
365 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
366 # so we can improve performance by filtering on a LIKE clause
367 $chunk = self
::getIpFragment( $start );
368 $dbr = wfGetDB( DB_REPLICA
);
369 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
371 # Fairly hard to make a malicious SQL statement out of hex characters,
372 # but stranger things have happened...
373 $safeStart = $dbr->addQuotes( $start );
374 $safeEnd = $dbr->addQuotes( $end );
376 return $dbr->makeList(
378 "ipb_range_start $like",
379 "ipb_range_start <= $safeStart",
380 "ipb_range_end >= $safeEnd",
387 * Get the component of an IP address which is certain to be the same between an IP
388 * address and a rangeblock containing that IP address.
389 * @param string $hex Hexadecimal IP representation
392 protected static function getIpFragment( $hex ) {
393 global $wgBlockCIDRLimit;
394 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
395 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
397 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
402 * Given a database row from the ipblocks table, initialize
404 * @param stdClass $row A row from the ipblocks table
406 protected function initFromRow( $row ) {
407 $this->setTarget( $row->ipb_address
);
408 if ( $row->ipb_by
) { // local user
409 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
410 } else { // foreign user
411 $this->setBlocker( $row->ipb_by_text
);
414 $this->mReason
= $row->ipb_reason
;
415 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
416 $this->mAuto
= $row->ipb_auto
;
417 $this->mHideName
= $row->ipb_deleted
;
418 $this->mId
= (int)$row->ipb_id
;
419 $this->mParentBlockId
= $row->ipb_parent_block_id
;
421 // I wish I didn't have to do this
422 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $row->ipb_expiry
);
424 $this->isHardblock( !$row->ipb_anon_only
);
425 $this->isAutoblocking( $row->ipb_enable_autoblock
);
427 $this->prevents( 'createaccount', $row->ipb_create_account
);
428 $this->prevents( 'sendemail', $row->ipb_block_email
);
429 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
433 * Create a new Block object from a database row
434 * @param stdClass $row Row from the ipblocks table
437 public static function newFromRow( $row ) {
439 $block->initFromRow( $row );
444 * Delete the row from the IP blocks table.
446 * @throws MWException
449 public function delete() {
450 if ( wfReadOnly() ) {
454 if ( !$this->getId() ) {
455 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
458 $dbw = wfGetDB( DB_MASTER
);
459 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
460 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
462 return $dbw->affectedRows() > 0;
466 * Insert a block into the block table. Will fail if there is a conflicting
467 * block (same name and options) already in the database.
469 * @param IDatabase $dbw If you have one available
470 * @return bool|array False on failure, assoc array on success:
471 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
473 public function insert( $dbw = null ) {
474 global $wgBlockDisablesLogin;
476 if ( $this->getSystemBlockType() !== null ) {
477 throw new MWException( 'Cannot insert a system block into the database' );
480 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
482 if ( $dbw === null ) {
483 $dbw = wfGetDB( DB_MASTER
);
486 # Periodic purge via commit hooks
487 if ( mt_rand( 0, 9 ) == 0 ) {
488 Block
::purgeExpired();
491 $row = $this->getDatabaseArray();
492 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
494 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
495 $affected = $dbw->affectedRows();
496 $this->mId
= $dbw->insertId();
498 # Don't collide with expired blocks.
499 # Do this after trying to insert to avoid locking.
501 # T96428: The ipb_address index uses a prefix on a field, so
502 # use a standard SELECT + DELETE to avoid annoying gap locks.
503 $ids = $dbw->selectFieldValues( 'ipblocks',
506 'ipb_address' => $row['ipb_address'],
507 'ipb_user' => $row['ipb_user'],
508 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
513 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
514 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
515 $affected = $dbw->affectedRows();
516 $this->mId
= $dbw->insertId();
521 $auto_ipd_ids = $this->doRetroactiveAutoblock();
523 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
524 // Change user login token to force them to be logged out.
525 $this->target
->setToken();
526 $this->target
->saveSettings();
529 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
536 * Update a block in the DB with new parameters.
537 * The ID field needs to be loaded first.
539 * @return bool|array False on failure, array on success:
540 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
542 public function update() {
543 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
544 $dbw = wfGetDB( DB_MASTER
);
546 $dbw->startAtomic( __METHOD__
);
550 $this->getDatabaseArray( $dbw ),
551 [ 'ipb_id' => $this->getId() ],
555 $affected = $dbw->affectedRows();
557 if ( $this->isAutoblocking() ) {
558 // update corresponding autoblock(s) (T50813)
561 $this->getAutoblockUpdateArray(),
562 [ 'ipb_parent_block_id' => $this->getId() ],
566 // autoblock no longer required, delete corresponding autoblock(s)
569 [ 'ipb_parent_block_id' => $this->getId() ],
574 $dbw->endAtomic( __METHOD__
);
577 $auto_ipd_ids = $this->doRetroactiveAutoblock();
578 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
585 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
586 * @param IDatabase $db
589 protected function getDatabaseArray( $db = null ) {
591 $db = wfGetDB( DB_REPLICA
);
593 $expiry = $db->encodeExpiry( $this->mExpiry
);
595 if ( $this->forcedTargetID
) {
596 $uid = $this->forcedTargetID
;
598 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
602 'ipb_address' => (string)$this->target
,
604 'ipb_by' => $this->getBy(),
605 'ipb_by_text' => $this->getByName(),
606 'ipb_reason' => $this->mReason
,
607 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
608 'ipb_auto' => $this->mAuto
,
609 'ipb_anon_only' => !$this->isHardblock(),
610 'ipb_create_account' => $this->prevents( 'createaccount' ),
611 'ipb_enable_autoblock' => $this->isAutoblocking(),
612 'ipb_expiry' => $expiry,
613 'ipb_range_start' => $this->getRangeStart(),
614 'ipb_range_end' => $this->getRangeEnd(),
615 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
616 'ipb_block_email' => $this->prevents( 'sendemail' ),
617 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
618 'ipb_parent_block_id' => $this->mParentBlockId
627 protected function getAutoblockUpdateArray() {
629 'ipb_by' => $this->getBy(),
630 'ipb_by_text' => $this->getByName(),
631 'ipb_reason' => $this->mReason
,
632 'ipb_create_account' => $this->prevents( 'createaccount' ),
633 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
634 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
639 * Retroactively autoblocks the last IP used by the user (if it is a user)
640 * blocked by this Block.
642 * @return array Block IDs of retroactive autoblocks made
644 protected function doRetroactiveAutoblock() {
646 # If autoblock is enabled, autoblock the LAST IP(s) used
647 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
648 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
650 $continue = Hooks
::run(
651 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
654 self
::defaultRetroactiveAutoblock( $this, $blockIds );
661 * Retroactively autoblocks the last IP used by the user (if it is a user)
662 * blocked by this Block. This will use the recentchanges table.
664 * @param Block $block
665 * @param array &$blockIds
667 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
670 // No IPs are in recentchanges table, so nothing to select
671 if ( !$wgPutIPinRC ) {
675 $dbr = wfGetDB( DB_REPLICA
);
677 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
678 $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
680 // Just the last IP used.
681 $options['LIMIT'] = 1;
683 $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
684 __METHOD__
, $options );
686 if ( !$res->numRows() ) {
687 # No results, don't autoblock anything
688 wfDebug( "No IP found to retroactively autoblock\n" );
690 foreach ( $res as $row ) {
692 $id = $block->doAutoblock( $row->rc_ip
);
702 * Checks whether a given IP is on the autoblock whitelist.
703 * TODO: this probably belongs somewhere else, but not sure where...
705 * @param string $ip The IP to check
708 public static function isWhitelistedFromAutoblocks( $ip ) {
709 // Try to get the autoblock_whitelist from the cache, as it's faster
710 // than getting the msg raw and explode()'ing it.
711 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
712 $lines = $cache->getWithSetCallback(
713 $cache->makeKey( 'ipb', 'autoblock', 'whitelist' ),
715 function ( $curValue, &$ttl, array &$setOpts ) {
716 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
718 return explode( "\n",
719 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
723 wfDebug( "Checking the autoblock whitelist..\n" );
725 foreach ( $lines as $line ) {
727 if ( substr( $line, 0, 1 ) !== '*' ) {
731 $wlEntry = substr( $line, 1 );
732 $wlEntry = trim( $wlEntry );
734 wfDebug( "Checking $ip against $wlEntry..." );
736 # Is the IP in this range?
737 if ( IP
::isInRange( $ip, $wlEntry ) ) {
738 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
741 wfDebug( " No match\n" );
749 * Autoblocks the given IP, referring to this Block.
751 * @param string $autoblockIP The IP to autoblock.
752 * @return int|bool Block ID if an autoblock was inserted, false if not.
754 public function doAutoblock( $autoblockIP ) {
755 # If autoblocks are disabled, go away.
756 if ( !$this->isAutoblocking() ) {
760 # Don't autoblock for system blocks
761 if ( $this->getSystemBlockType() !== null ) {
762 throw new MWException( 'Cannot autoblock from a system block' );
765 # Check for presence on the autoblock whitelist.
766 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
770 // Avoid PHP 7.1 warning of passing $this by reference
772 # Allow hooks to cancel the autoblock.
773 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
774 wfDebug( "Autoblock aborted by hook.\n" );
778 # It's okay to autoblock. Go ahead and insert/update the block...
780 # Do not add a *new* block if the IP is already blocked.
781 $ipblock = Block
::newFromTarget( $autoblockIP );
783 # Check if the block is an autoblock and would exceed the user block
784 # if renewed. If so, do nothing, otherwise prolong the block time...
785 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
786 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
788 # Reset block timestamp to now and its expiry to
789 # $wgAutoblockExpiry in the future
790 $ipblock->updateTimestamp();
795 # Make a new block object with the desired properties.
796 $autoblock = new Block
;
797 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
798 $autoblock->setTarget( $autoblockIP );
799 $autoblock->setBlocker( $this->getBlocker() );
800 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
801 ->inContentLanguage()->plain();
802 $timestamp = wfTimestampNow();
803 $autoblock->mTimestamp
= $timestamp;
804 $autoblock->mAuto
= 1;
805 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
806 # Continue suppressing the name if needed
807 $autoblock->mHideName
= $this->mHideName
;
808 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
809 $autoblock->mParentBlockId
= $this->mId
;
811 if ( $this->mExpiry
== 'infinity' ) {
812 # Original block was indefinite, start an autoblock now
813 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
815 # If the user is already blocked with an expiry date, we don't
816 # want to pile on top of that.
817 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
820 # Insert the block...
821 $status = $autoblock->insert();
828 * Check if a block has expired. Delete it if it is.
831 public function deleteIfExpired() {
832 if ( $this->isExpired() ) {
833 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
837 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
845 * Has the block expired?
848 public function isExpired() {
849 $timestamp = wfTimestampNow();
850 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
852 if ( !$this->mExpiry
) {
855 return $timestamp > $this->mExpiry
;
860 * Is the block address valid (i.e. not a null string?)
863 public function isValid() {
864 return $this->getTarget() != null;
868 * Update the timestamp on autoblocks.
870 public function updateTimestamp() {
871 if ( $this->mAuto
) {
872 $this->mTimestamp
= wfTimestamp();
873 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
875 $dbw = wfGetDB( DB_MASTER
);
876 $dbw->update( 'ipblocks',
878 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
879 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
882 'ipb_id' => $this->getId(),
890 * Get the IP address at the start of the range in Hex form
891 * @throws MWException
892 * @return string IP in Hex form
894 public function getRangeStart() {
895 switch ( $this->type
) {
896 case self
::TYPE_USER
:
899 return IP
::toHex( $this->target
);
900 case self
::TYPE_RANGE
:
901 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
904 throw new MWException( "Block with invalid type" );
909 * Get the IP address at the end of the range in Hex form
910 * @throws MWException
911 * @return string IP in Hex form
913 public function getRangeEnd() {
914 switch ( $this->type
) {
915 case self
::TYPE_USER
:
918 return IP
::toHex( $this->target
);
919 case self
::TYPE_RANGE
:
920 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
923 throw new MWException( "Block with invalid type" );
928 * Get the user id of the blocking sysop
930 * @return int (0 for foreign users)
932 public function getBy() {
933 $blocker = $this->getBlocker();
934 return ( $blocker instanceof User
)
940 * Get the username of the blocking sysop
944 public function getByName() {
945 $blocker = $this->getBlocker();
946 return ( $blocker instanceof User
)
947 ?
$blocker->getName()
948 : (string)$blocker; // username
955 public function getId() {
960 * Get the system block type, if any
961 * @return string|null
963 public function getSystemBlockType() {
964 return $this->systemBlockType
;
968 * Get/set a flag determining whether the master is used for reads
970 * @param bool|null $x
973 public function fromMaster( $x = null ) {
974 return wfSetVar( $this->mFromMaster
, $x );
978 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
979 * @param bool|null $x
982 public function isHardblock( $x = null ) {
983 wfSetVar( $this->isHardblock
, $x );
985 # You can't *not* hardblock a user
986 return $this->getType() == self
::TYPE_USER
988 : $this->isHardblock
;
992 * @param null|bool $x
995 public function isAutoblocking( $x = null ) {
996 wfSetVar( $this->isAutoblocking
, $x );
998 # You can't put an autoblock on an IP or range as we don't have any history to
999 # look over to get more IPs from
1000 return $this->getType() == self
::TYPE_USER
1001 ?
$this->isAutoblocking
1006 * Get/set whether the Block prevents a given action
1008 * @param string $action Action to check
1009 * @param bool|null $x Value for set, or null to just get value
1010 * @return bool|null Null for unrecognized rights.
1012 public function prevents( $action, $x = null ) {
1013 global $wgBlockDisablesLogin;
1015 switch ( $action ) {
1017 # For now... <evil laugh>
1020 case 'createaccount':
1021 $res = wfSetVar( $this->mCreateAccount
, $x );
1024 $res = wfSetVar( $this->mBlockEmail
, $x );
1026 case 'editownusertalk':
1027 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1033 if ( !$res && $wgBlockDisablesLogin ) {
1034 // If a block would disable login, then it should
1035 // prevent any action that all users cannot do
1037 $res = $anon->isAllowed( $action ) ?
$res : true;
1044 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1045 * @return string Text is escaped
1047 public function getRedactedName() {
1048 if ( $this->mAuto
) {
1049 return Html
::rawElement(
1051 [ 'class' => 'mw-autoblockid' ],
1052 wfMessage( 'autoblockid', $this->mId
)
1055 return htmlspecialchars( $this->getTarget() );
1060 * Get a timestamp of the expiry for autoblocks
1062 * @param string|int $timestamp
1065 public static function getAutoblockExpiry( $timestamp ) {
1066 global $wgAutoblockExpiry;
1068 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1072 * Purge expired blocks from the ipblocks table
1074 public static function purgeExpired() {
1075 if ( wfReadOnly() ) {
1079 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
1080 wfGetDB( DB_MASTER
),
1082 function ( IDatabase
$dbw, $fname ) {
1085 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1093 * Given a target and the target's type, get an existing Block object if possible.
1094 * @param string|User|int $specificTarget A block target, which may be one of several types:
1095 * * A user to block, in which case $target will be a User
1096 * * An IP to block, in which case $target will be a User generated by using
1097 * User::newFromName( $ip, false ) to turn off name validation
1098 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1099 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1101 * Calling this with a user, IP address or range will not select autoblocks, and will
1102 * only select a block where the targets match exactly (so looking for blocks on
1103 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1104 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1105 * affects that target (so for an IP address, get ranges containing that IP; and also
1106 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1107 * @param bool $fromMaster Whether to use the DB_MASTER database
1108 * @return Block|null (null if no relevant block could be found). The target and type
1109 * of the returned Block will refer to the actual block which was found, which might
1110 * not be the same as the target you gave if you used $vagueTarget!
1112 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1113 list( $target, $type ) = self
::parseTarget( $specificTarget );
1114 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1115 return Block
::newFromID( $target );
1117 } elseif ( $target === null && $vagueTarget == '' ) {
1118 # We're not going to find anything useful here
1119 # Be aware that the == '' check is explicit, since empty values will be
1120 # passed by some callers (T31116)
1123 } elseif ( in_array(
1125 [ Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ] )
1127 $block = new Block();
1128 $block->fromMaster( $fromMaster );
1130 if ( $type !== null ) {
1131 $block->setTarget( $target );
1134 if ( $block->newLoad( $vagueTarget ) ) {
1142 * Get all blocks that match any IP from an array of IP addresses
1144 * @param array $ipChain List of IPs (strings), usually retrieved from the
1145 * X-Forwarded-For header of the request
1146 * @param bool $isAnon Exclude anonymous-only blocks if false
1147 * @param bool $fromMaster Whether to query the master or replica DB
1148 * @return array Array of Blocks
1151 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1152 if ( !count( $ipChain ) ) {
1157 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1158 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1159 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1160 # necessarily trust the header given to us, make sure that we are only
1161 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1162 # Do not treat private IP spaces as special as it may be desirable for wikis
1163 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1164 if ( !IP
::isValid( $ipaddr ) ) {
1167 # Don't check trusted IPs (includes local squids which will be in every request)
1168 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1171 # Check both the original IP (to check against single blocks), as well as build
1172 # the clause to check for rangeblocks for the given IP.
1173 $conds['ipb_address'][] = $ipaddr;
1174 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1177 if ( !count( $conds ) ) {
1181 if ( $fromMaster ) {
1182 $db = wfGetDB( DB_MASTER
);
1184 $db = wfGetDB( DB_REPLICA
);
1186 $conds = $db->makeList( $conds, LIST_OR
);
1188 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1190 $selectFields = array_merge(
1191 [ 'ipb_range_start', 'ipb_range_end' ],
1192 Block
::selectFields()
1194 $rows = $db->select( 'ipblocks',
1201 foreach ( $rows as $row ) {
1202 $block = self
::newFromRow( $row );
1203 if ( !$block->isExpired() ) {
1212 * From a list of multiple blocks, find the most exact and strongest Block.
1214 * The logic for finding the "best" block is:
1215 * - Blocks that match the block's target IP are preferred over ones in a range
1216 * - Hardblocks are chosen over softblocks that prevent account creation
1217 * - Softblocks that prevent account creation are chosen over other softblocks
1218 * - Other softblocks are chosen over autoblocks
1219 * - If there are multiple exact or range blocks at the same level, the one chosen
1221 * This should be used when $blocks where retrieved from the user's IP address
1222 * and $ipChain is populated from the same IP address information.
1224 * @param array $blocks Array of Block objects
1225 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1226 * a block is to the server, and if a block matches exactly, or is in a range.
1227 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1229 * @throws MWException
1230 * @return Block|null The "best" block from the list
1232 public static function chooseBlock( array $blocks, array $ipChain ) {
1233 if ( !count( $blocks ) ) {
1235 } elseif ( count( $blocks ) == 1 ) {
1239 // Sort hard blocks before soft ones and secondarily sort blocks
1240 // that disable account creation before those that don't.
1241 usort( $blocks, function ( Block
$a, Block
$b ) {
1242 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1243 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1244 return strcmp( $bWeight, $aWeight ); // highest weight first
1247 $blocksListExact = [
1249 'disable_create' => false,
1253 $blocksListRange = [
1255 'disable_create' => false,
1259 $ipChain = array_reverse( $ipChain );
1261 /** @var Block $block */
1262 foreach ( $blocks as $block ) {
1263 // Stop searching if we have already have a "better" block. This
1264 // is why the order of the blocks matters
1265 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1267 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1271 foreach ( $ipChain as $checkip ) {
1272 $checkipHex = IP
::toHex( $checkip );
1273 if ( (string)$block->getTarget() === $checkip ) {
1274 if ( $block->isHardblock() ) {
1275 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1276 } elseif ( $block->prevents( 'createaccount' ) ) {
1277 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1278 } elseif ( $block->mAuto
) {
1279 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1281 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1283 // We found closest exact match in the ip list, so go to the next Block
1285 } elseif ( array_filter( $blocksListExact ) == []
1286 && $block->getRangeStart() <= $checkipHex
1287 && $block->getRangeEnd() >= $checkipHex
1289 if ( $block->isHardblock() ) {
1290 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1291 } elseif ( $block->prevents( 'createaccount' ) ) {
1292 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1293 } elseif ( $block->mAuto
) {
1294 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1296 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1303 if ( array_filter( $blocksListExact ) == [] ) {
1304 $blocksList = &$blocksListRange;
1306 $blocksList = &$blocksListExact;
1309 $chosenBlock = null;
1310 if ( $blocksList['hard'] ) {
1311 $chosenBlock = $blocksList['hard'];
1312 } elseif ( $blocksList['disable_create'] ) {
1313 $chosenBlock = $blocksList['disable_create'];
1314 } elseif ( $blocksList['other'] ) {
1315 $chosenBlock = $blocksList['other'];
1316 } elseif ( $blocksList['auto'] ) {
1317 $chosenBlock = $blocksList['auto'];
1319 throw new MWException( "Proxy block found, but couldn't be classified." );
1322 return $chosenBlock;
1326 * From an existing Block, get the target and the type of target.
1327 * Note that, except for null, it is always safe to treat the target
1328 * as a string; for User objects this will return User::__toString()
1329 * which in turn gives User::getName().
1331 * @param string|int|User|null $target
1332 * @return array( User|String|null, Block::TYPE_ constant|null )
1334 public static function parseTarget( $target ) {
1335 # We may have been through this before
1336 if ( $target instanceof User
) {
1337 if ( IP
::isValid( $target->getName() ) ) {
1338 return [ $target, self
::TYPE_IP
];
1340 return [ $target, self
::TYPE_USER
];
1342 } elseif ( $target === null ) {
1343 return [ null, null ];
1346 $target = trim( $target );
1348 if ( IP
::isValid( $target ) ) {
1349 # We can still create a User if it's an IP address, but we need to turn
1350 # off validation checking (which would exclude IP addresses)
1352 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1356 } elseif ( IP
::isValidBlock( $target ) ) {
1357 # Can't create a User from an IP range
1358 return [ IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
];
1361 # Consider the possibility that this is not a username at all
1362 # but actually an old subpage (bug #29797)
1363 if ( strpos( $target, '/' ) !== false ) {
1364 # An old subpage, drill down to the user behind it
1365 $target = explode( '/', $target )[0];
1368 $userObj = User
::newFromName( $target );
1369 if ( $userObj instanceof User
) {
1370 # Note that since numbers are valid usernames, a $target of "12345" will be
1371 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1372 # since hash characters are not valid in usernames or titles generally.
1373 return [ $userObj, Block
::TYPE_USER
];
1375 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1376 # Autoblock reference in the form "#12345"
1377 return [ substr( $target, 1 ), Block
::TYPE_AUTO
];
1381 return [ null, null ];
1386 * Get the type of target for this particular block
1387 * @return int Block::TYPE_ constant, will never be TYPE_ID
1389 public function getType() {
1396 * Get the target and target type for this particular Block. Note that for autoblocks,
1397 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1398 * in this situation.
1399 * @return array( User|String, Block::TYPE_ constant )
1400 * @todo FIXME: This should be an integral part of the Block member variables
1402 public function getTargetAndType() {
1403 return [ $this->getTarget(), $this->getType() ];
1407 * Get the target for this particular Block. Note that for autoblocks,
1408 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1409 * in this situation.
1410 * @return User|string
1412 public function getTarget() {
1413 return $this->target
;
1419 * @return mixed|string
1421 public function getExpiry() {
1422 return $this->mExpiry
;
1426 * Set the target for this block, and update $this->type accordingly
1427 * @param mixed $target
1429 public function setTarget( $target ) {
1430 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1434 * Get the user who implemented this block
1435 * @return User|string Local User object or string for a foreign user
1437 public function getBlocker() {
1438 return $this->blocker
;
1442 * Set the user who implemented (or will implement) this block
1443 * @param User|string $user Local User object or username string for foreign users
1445 public function setBlocker( $user ) {
1446 $this->blocker
= $user;
1450 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1451 * the same as the block's, to a maximum of 24 hours.
1453 * @param WebResponse $response The response on which to set the cookie.
1455 public function setCookie( WebResponse
$response ) {
1456 // Calculate the default expiry time.
1457 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1459 // Use the Block's expiry time only if it's less than the default.
1460 $expiryTime = $this->getExpiry();
1461 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1462 $expiryTime = $maxExpiryTime;
1465 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1466 $expiryValue = DateTime
::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1467 $cookieOptions = [ 'httpOnly' => false ];
1468 $cookieValue = $this->getCookieValue();
1469 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1473 * Unset the 'BlockID' cookie.
1475 * @param WebResponse $response The response on which to unset the cookie.
1477 public static function clearCookie( WebResponse
$response ) {
1478 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1482 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1483 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1485 * @return string The block ID, probably concatenated with "!" and the HMAC.
1487 public function getCookieValue() {
1488 $config = RequestContext
::getMain()->getConfig();
1489 $id = $this->getId();
1490 $secretKey = $config->get( 'SecretKey' );
1491 if ( !$secretKey ) {
1492 // If there's no secret key, don't append a HMAC.
1495 $hmac = MWCryptHash
::hmac( $id, $secretKey, false );
1496 $cookieValue = $id . '!' . $hmac;
1497 return $cookieValue;
1501 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1502 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1503 * @param string $cookieValue The string in which to find the ID.
1504 * @return integer|null The block ID, or null if the HMAC is present and invalid.
1506 public static function getIdFromCookieValue( $cookieValue ) {
1507 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1508 $bangPos = strpos( $cookieValue, '!' );
1509 $id = ( $bangPos === false ) ?
$cookieValue : substr( $cookieValue, 0, $bangPos );
1510 // Get the site-wide secret key.
1511 $config = RequestContext
::getMain()->getConfig();
1512 $secretKey = $config->get( 'SecretKey' );
1513 if ( !$secretKey ) {
1514 // If there's no secret key, just use the ID as given.
1517 $storedHmac = substr( $cookieValue, $bangPos +
1 );
1518 $calculatedHmac = MWCryptHash
::hmac( $id, $secretKey, false );
1519 if ( $calculatedHmac === $storedHmac ) {
1527 * Get the key and parameters for the corresponding error message.
1530 * @param IContextSource $context
1533 public function getPermissionsError( IContextSource
$context ) {
1534 $blocker = $this->getBlocker();
1535 if ( $blocker instanceof User
) { // local user
1536 $blockerUserpage = $blocker->getUserPage();
1537 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1538 } else { // foreign user
1542 $reason = $this->mReason
;
1543 if ( $reason == '' ) {
1544 $reason = $context->msg( 'blockednoreason' )->text();
1547 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1548 * This could be a username, an IP range, or a single IP. */
1549 $intended = $this->getTarget();
1551 $systemBlockType = $this->getSystemBlockType();
1553 $lang = $context->getLanguage();
1555 $systemBlockType !== null
1556 ?
'systemblockedtext'
1557 : ( $this->mAuto ?
'autoblockedtext' : 'blockedtext' ),
1560 $context->getRequest()->getIP(),
1562 $systemBlockType !== null ?
$systemBlockType : $this->getId(),
1563 $lang->formatExpiry( $this->mExpiry
),
1565 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),